package com.weicx.wuzhiops.service.impl;

import com.weicx.wuzhiops.constant.MessageConstant;
import com.weicx.wuzhiops.constant.event.EventKeys;
import com.weicx.wuzhiops.entity.UserInfo;
import com.weicx.wuzhiops.exception.InvalidArgumentException;
import com.weicx.wuzhiops.model.request.UserLoginRequest;
import com.weicx.wuzhiops.service.AuthenticateService;
import com.weicx.wuzhiops.service.UserInfoService;
import com.weicx.wuzhiops.util.EventParamsHolder;
import com.weicx.wuzhiops.util.JwtUtil;
import com.weicx.wuzhiops.util.ValueMix;
import com.weicx.wuzhiops.vo.UserLoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author:
 * @date: 2022-12-06 11:07:08
 * @since: 1.0
 */
@Service
public class AuthenticateServiceImpl implements AuthenticateService {


    private static final Logger log = LoggerFactory.getLogger(AuthenticateServiceImpl.class);

    @Resource
    private UserInfoService userInfoService;


    @Override
    public UserLoginVO login(UserLoginRequest loginRequest) {

        UserInfo userInfo = userInfoService.getByUserName(loginRequest.getUsername());
        if (null == userInfo) {
            throw new InvalidArgumentException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        String pwdSign = userInfo.getPassword();
        // 前端输入的密码md5加密的结果
        String reqPwd = loginRequest.getPassword();
        boolean valid = ValueMix.validPassword(loginRequest.getPassword(), userInfo.getSalt(), pwdSign);
        if (!valid) {
            throw new InvalidArgumentException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        Long userId = userInfo.getId();
        // 更新最近登录时间
        userInfoService.updateLastLoginTime(userId);
        String loginToken = JwtUtil.getLoginToken(userId, reqPwd);
        UserLoginVO loginVO = new UserLoginVO();
        loginVO.setUserId(userId);
        loginVO.setToken(loginToken);
        loginVO.setNickname(userInfo.getNickname());
        loginVO.setUsername(userInfo.getUsername());

        // 设置日志参数
        EventParamsHolder.addParam(EventKeys.INNER_USER_ID, userInfo.getId());
        EventParamsHolder.addParam(EventKeys.INNER_USER_NAME, userInfo.getUsername());
        return loginVO;
    }
}
